import {Injectable} from '@angular/core';
import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler,
  HttpHeaders,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {environment} from '../../environments/environment';
import {AppService} from '../app.service';
import {CommonTool} from '../common/common.tool';
import {catchError, mergeMap} from 'rxjs/operators';
import {Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd';
import {LoginDto} from './base.model';

@Injectable()
export class BaseHttpInterceptor implements HttpInterceptor {
  constructor(private router: Router,
              public appService: AppService,
              private message: NzMessageService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = CommonTool.getCookie(environment.tokenKey);
    let headers = {};
    if (CommonTool.notNull(token)) {
      const tokenInfo: LoginDto = new LoginDto(JSON.parse(token));
      if (!CommonTool.notNull(req.headers.get('token'))) {
        headers = {token: tokenInfo.accessToken ? tokenInfo.accessToken : ''};
      }
    }
    const authReq = req.clone({headers: new HttpHeaders(headers)});
    // @ts-ignore
    return next.handle(authReq).pipe(
      mergeMap((event: any) => {
        // 正常返回，处理具体返回参数
        if (event instanceof HttpResponse && event.status === 200) {
        }
        return of(event);
      }),
      catchError((err: HttpErrorResponse) => {
        this.appService.setLoading(false);
        if (err && err.error && err.error.message) {
          this.message.error(err.error.message);
        } else {
          console.error(err);
        }
        if (err.status === 400 && err.error.code === 'o_002') {
          this.router.navigate(['/login']);
        }
        return of(err);
      }));
  }

}
